package com.fhz.day016;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuView;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fhz.day016.adapter.SongAdapter;
import com.fhz.day016.comm.PlayModelUtil;
import com.fhz.day016.entity.Song;
import com.fhz.day016.utils.SongDataUtil;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private ListView lv;
    private SeekBar seekBar;
    private ImageView songImage;
    private TextView songTitle;
    private ImageView pre;
    private ImageView pauseRestart;
    private ImageView next;
    private ImageView model;
    private Banner banner;

    private SongAdapter songAdapter;
    private List<Song> songList;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private int index = 0;
    private Timer timer;
    private int playModel = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        List<String> bannerList  = new ArrayList<>();
        bannerList.add("https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg");
        bannerList.add("http://39.106.204.190:7777/image/36024806.jpg");
        bannerList.add("http://39.106.204.190:7777/image/1405283464.jpg");
        //轮播图
        banner.setImages(bannerList);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        banner.start();

        //动态的请求权限
        requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
        },100);

        //网上. //本地
        //本地是不是需要权限呢?
        //

        songList = new ArrayList<>();
        songAdapter = new SongAdapter(songList, this);
        lv.setAdapter(songAdapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                play(position);
            }
        });

        //取到当前歌曲的最大值

        //倒计时用于更新进度条
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                seekBar.setMax(mediaPlayer.getDuration());
                seekBar.setProgress(mediaPlayer.getCurrentPosition());
            }
        },0,1000);


        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    private void play(int position) {

        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(songList.get(position).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            //播放完成后的逻辑
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    switch (playModel){
                        case PlayModelUtil.SINGEL:
                            play(index);
                            break;
                        case PlayModelUtil.RANDOM:
                            int i = new Random().nextInt(songList.size()); //4 .0-3
                            index = i;
                            play(i);
                            break;
                        case PlayModelUtil.OREDER:
                            next();
                            break;
                    }
                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Toast.makeText(MainActivity.this, "播放错误", Toast.LENGTH_SHORT).show();
                    return false;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        change();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //请求本地的数据源了
//            ContentResolver contentResolver = getContentResolver();
//            contentResolver.query(?)
            List<Song> dataList = SongDataUtil.getSongDataUtil().getDataList(this);
            songList.addAll(dataList);
            songAdapter.notifyDataSetChanged();
        }else{

        }
    }

    private void initView() {

        banner = (Banner) findViewById(R.id.banner);

        lv = (ListView) findViewById(R.id.lv);
        seekBar = (SeekBar) findViewById(R.id.seek_bar);
        songImage = (ImageView) findViewById(R.id.song_image);
        songTitle = (TextView) findViewById(R.id.song_title);
        pre = (ImageView) findViewById(R.id.pre);
        pauseRestart = (ImageView) findViewById(R.id.pause_restart);
        next = (ImageView) findViewById(R.id.next);
        model = (ImageView) findViewById(R.id.model);
    }

    public void pause_restart(View view) {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            pauseRestart.setImageResource(R.drawable.play);
        }else{
            mediaPlayer.start();
            pauseRestart.setImageResource(R.drawable.pause);
        }
    }

    public void next(View view) {
       next();
    }

    private void next() {
        index++;
        if(index >= songList.size()){
            index = 0;
        }
        play(index);
    }

    public void pre(View view) {
        index--;
        if(index <= 0){
            index = 0;
        }
        play(index);
    }

    public void model(View view) {
        PopupWindow popupWindow = new PopupWindow(this);
        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);

        TextView textView = inflate.findViewById(R.id.singel);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放单曲
                playModel = PlayModelUtil.SINGEL;
                Toast.makeText(MainActivity.this, "单曲", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        TextView order = inflate.findViewById(R.id.order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放单曲
                playModel = PlayModelUtil.OREDER;
                Toast.makeText(MainActivity.this, "顺序", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        TextView random = inflate.findViewById(R.id.random);
        random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放单曲
                playModel = PlayModelUtil.RANDOM;
                Toast.makeText(MainActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });


        popupWindow.setContentView(inflate);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        View inflate1 = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        popupWindow.showAtLocation(inflate1, Gravity.BOTTOM,0,280);
    }

    //改变播放的图片和文字
    public void change(){
        Glide.with(this)
                .load(SongDataUtil.getAlbum(this,Integer.parseInt(songList.get(index).getAlbum())))
                .into(songImage);
        songTitle.setText(songList.get(index).getTitle());
    }
}